package com.niit.onlinemusicserver34.common;

import io.jsonwebtoken.*;

import java.util.Date;

public class JwtUtils {

    public static final String SECRET_KEY = "hanliang123456";
    // 过期时间，单位为秒
    private static final long EXPIRATION_TIME = 7*24*60*60; // 7天

    /**
     * 生成 JWT   subject 用户信息
     * @param subject
     * @return
     */
    public static String generateToken(String subject) {
        // 计算过期时间
        Date expirationDate = new Date(System.currentTimeMillis() + EXPIRATION_TIME * 1000);
        String jwt = Jwts.builder()
                .setSubject(subject)
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.HS512, SECRET_KEY)
                .compact();
        return jwt;
    }

    //解析 JWT
    public static Claims parseToken(String jwt) {
        Claims claims = Jwts.parser()
                .setSigningKey(SECRET_KEY)
                .parseClaimsJws(jwt)
                .getBody();
        return claims;
    }

    //验证JWT是否过期
    public static boolean isTokenExpired(String jwt) {
        try {
            Claims claims = parseToken(jwt);
            Date expirationDate = claims.getExpiration();
            return expirationDate.before(new Date());
        } catch (Exception e) {
            //过期会抛异常，所以直接捕捉  返回ture代表已过期
            throw new ExpiredJwtException(null, null, "Token已经过期");
            //return true;
        }
    }

    public static boolean verify(String token) {
        try {
            Jwts.parser()
                    .setSigningKey(SECRET_KEY)
                    .setAllowedClockSkewSeconds(10)
                    .parseClaimsJws(token)
                    .getBody();
            return true;
        } catch (Exception e) {
//            throw new JwtException("非法的Token");
            return false;
        }
    }

    //临时测试
    public static void main(String[] args) {
        String token = generateToken("hanliang");
        System.out.println(token);
        System.out.println(parseToken(token));
        System.out.println(isTokenExpired(token));
    }
}
